﻿using ApplicationBase.Core.Context;
using MediatR;

namespace ApplicationBase.Core.Command
{
    public class InjectServiceContextBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
        where TRequest : IRequest<TResponse>
    {
        private readonly IServiceContext _serviceContext;
        public InjectServiceContextBehavior(IServiceContext serviceContext)
        {
            _serviceContext = serviceContext;
        } 

        public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
        {
            if (request is BaseCommand<TResponse> cmd)
            {
                cmd.ServiceContext = _serviceContext;
            }
            return await next();
        }
    }
}
